/*
 * The MiniQt Library
 *
 * Copyright (C) 1999 Sandro Sigala <ssigala@globalnet.it>
 */

#include <string.h>
#include <windows.h>

#include "qapplication.h"

HINSTANCE hInstance; // Used outside for CreateWindow() calls

int qmain(int argc, char **argv);

#define MAX_ARGUMENTS		128

static void unpack_lpCmdLine(const char *s, int& argc, char *argv[])
{
	int argno = 0, argidx = 0;
	for (; *s != '\0'; ++s) {
		if (*s == ' ') {
			while (*s == ' ')
				++s;
			if (*s == '\0')
				break;
			++argno;
			argidx = 0;
		}
		if (argidx == 0) {
			// Allocate a new argument
			argv[argno] = new char[strlen(s) + 1];
			memset(argv[argno], 0, strlen(s) + 1);
			++argc;
		}
		argv[argno][argidx++] = *s;
	}
	argv[argc] = 0;
}

int WinMain(HINSTANCE hInst, HINSTANCE /*hPrevInstance*/, LPSTR lpCmdLine, int /*nShowCmd*/)
{
#ifdef DEBUG
	qDebugSetTypes(4, "startup", "obj", "moc", "wid");
#endif

        hInstance = hInst;

#ifdef DEBUG
	qDebug("startup", "command line: \"%s\"", lpCmdLine);
#endif
	int argc = 1;
        char *argv[MAX_ARGUMENTS];
	argv[0] = "appname"; // XXX
	unpack_lpCmdLine(lpCmdLine, argc, &argv[1]);
#ifdef DEBUG
	for (int i = 0; i < argc; ++i)
		qDebug("startup", "argv[%d]: \"%s\"", i, argv[i]);
#endif
        int retvalue = qmain(argc, argv);
	for (int i = 1; i < argc; ++i)
		delete [] argv[i];
	return retvalue;
}
